package com.chenchen.code.guava.io;

import com.google.common.io.ByteSource;
import com.google.common.io.Closer;
import com.google.common.io.Files;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description:
 * @author chenchen
 * @date 2019/5/13 10:53
 */
public class CloserTest {

    private final String source = "D:\\guavatest\\source.txt";
    private final String target = "D:\\guavatest\\target.txt";

    //gauva解决方案
    @Test
    public void testCloser() throws IOException {
        ByteSource byteSource = Files.asByteSource(new File(source));
        Closer closer = Closer.create();
        try {
            InputStream inputStream = closer.register(byteSource.openStream());
        } catch (Throwable e) {
            throw closer.rethrow(e);
        } finally {
            closer.close();
        }
    }

    //throw new IndexOutOfBoundsException("3333"); 被throw new RuntimeException("2222");覆盖
    @Test(expected = RuntimeException.class)
    public void testTryCatchFinally() {
        try {
            System.out.println("work area.");
            throw new IllegalArgumentException("1111");
        } catch (Exception e) {
            System.out.println("exception area");
            throw new RuntimeException("2222");
        } finally {
            System.out.println("finally area");
            throw new IndexOutOfBoundsException("3333");
        }
    }

    //自己解决方案
    @Test
    public void testTryCatch() {
        Throwable t = null;
        try {
            throw new RuntimeException("1");
        } catch (Exception e) {
            t = e;
            throw e;
        } finally {
            try {
                throw new RuntimeException("2");
            } catch (Exception e) {
                t.addSuppressed(e);
            }
        }
    }

}
